package com.zhunaer.dao.impl;

import com.zhunaer.dao.UserDao;
import com.zhunaer.entity.User;
import com.zhunaer.utils.JDBCUtils;

import java.sql.*;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 用户数据访问对象实现类
 * 提供对用户表的增删改查操作
 */
public class UserDaoImpl implements UserDao {

    /**
     * 根据用户名查询用户信息
     * @param username 要查询的用户名
     * @return 查询到的用户对象，如果不存在则返回null
     */
    @Override
    public User findByUsername(String username) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "SELECT * FROM users WHERE username = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                User user = new User();
                user.setUserId(rs.getInt("user_id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setRealName(rs.getString("real_name"));
                user.setPhone(rs.getString("phone"));
                user.setBalance(rs.getBigDecimal("balance"));
                user.setCreatedAt(new Date(rs.getTimestamp("created_at").getTime()));
                return user;
            }
            return null;
        } catch (SQLException e) {
            throw new RuntimeException("查询用户失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, rs);
        }
    }

    /**
     * 创建新用户
     * @param user 要创建的用户对象
     * @return 创建成功返回用户ID，失败返回-1
     */
    @Override
    public int createUser(User user) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "INSERT INTO users(username, password, real_name, phone) VALUES(?,?,?,?)";
            pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getRealName());
            pstmt.setString(4, user.getPhone());

            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                ResultSet rs = pstmt.getGeneratedKeys();
                if (rs.next()) {
                    return rs.getInt(1);
                }
            }
            return -1;
        } catch (SQLException e) {
            throw new RuntimeException("创建用户失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, null);
        }
    }

    /**
     * 更新用户信息
     * @param user 包含更新信息的用户对象
     * @return 受影响的行数
     */
    @Override
    public int updateUser(User user) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "UPDATE users SET real_name=?, phone=? WHERE user_id=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, user.getRealName());
            pstmt.setString(2, user.getPhone());
            pstmt.setInt(3, user.getUserId());
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("更新用户信息失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, null);
        }
    }

    /**
     * 更新用户余额
     * @param userId 用户ID
     * @param amount 要更新(增加/减少)的金额
     * @return 受影响的行数
     */
    @Override
    public int updateBalance(int userId, BigDecimal amount) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = JDBCUtils.getConnection();
            String sql = "UPDATE users SET balance = balance + ? WHERE user_id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setBigDecimal(1, amount);
            pstmt.setInt(2, userId);
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("更新余额失败", e);
        } finally {
            JDBCUtils.close(conn, pstmt, null);
        }
    }
}